package com.zprmb.udzt;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.crypto.Cipher;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.zprmb.udzt.gesture.GestureEditActivity;
import com.zprmb.udzt.gesture.GestureVerifyActivity;
import com.zprmb.udzt.rsa.Base64;
import com.zprmb.udzt.rsa.ConfigureEncryptAndDecrypt;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.util.UpdateManager;
import com.zprmb.udzt.view.LoadingDialog;
/**
 * BaseAtivity
 * @author shenshao
 *
 */
public class BaseActivityTest extends FragmentActivity {
	
	//private BbtApplication app;
	private LoadingDialog ld;
	private SharedPreferences sp,sha;
	private String description;
	private String url;
	private String version; 
	private boolean forceUpdate;
	private Dialog dialog; 
	private TelephonyManager tm;
	private PushAgent mPushAgent;
	private TextView tv_title;
	public static final String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCb9I0Uohf2nTP3zyOk7q+Fuo7szbp0XYFzW0ik52DGnLH6TGooO1DIjbgQ8GgsW6YH0xby/R4eWc1U4U64jSGKiIcYRmUQvSWuPiKk8qT9g6ukMcMmNg3nWH2KOWPyYADOPL3w1maVB6+SZ/G8c9pTqjQlpLmTFM9sFy09v2+RGQIDAQAB";
private RelativeLayout rl_back;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sha= getSharedPreferences("coupon", MODE_PRIVATE);
		sp = getSharedPreferences("config", MODE_PRIVATE);
				 tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
//				 ScreenListener l = new ScreenListener(this);
				  mPushAgent = PushAgent.getInstance(this);
			        mPushAgent.onAppStart();
			      
//				 l.begin(new ScreenStateListener() {
//
//			            @Override
//			            public void onUserPresent() {
//			                Log.e("onUserPresent", "onUserPresent");
//			            }
//
//			            @Override
//			            public void onScreenOn() {
//			                Log.e("onScreenOn", "onScreenOn");
//			            }
//
//			            @Override
//			            public void onScreenOff() {
//			                Log.e("onScreenOff", "onScreenOff");
//			                Editor ed=sp.edit();
//			   			 ed.putString("time", ondata());
//			   			 ed.putInt("isopen",1 );
//						ed.putString("isTop", "1");
//			   			 ed.commit();
//			            }
//			        });
		//app = ((BbtApplication) getApplication());
		//app.addActvity(this);
		//ld = new LoadingDialog(this);
		//setImmersionStatus();
	}
	
	private void setImmersionStatus() {
		if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
			// 透明状态栏
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			//getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}
	}
	//动画
	public void setdisappear_bottom_in(Activity activity,View view){
	Animation	anim=AnimationUtils.loadAnimation(activity,
				R.anim.disappear_bottom_right_in);
	view.setAnimation(anim);
	}
	public void setflip_horizontal_in(Activity activity,View view){
		Animation	anim=AnimationUtils.loadAnimation(activity,
					R.anim.flip_horizontal_in);
		view.setAnimation(anim);
		}
	public String getdeviceId(){
		return tm.getDeviceId();
		
	}
	public LinearLayout setContentInview(Activity activity){
		LinearLayout	view=(LinearLayout)activity.findViewById(R.id.li_all);
			
			return view;
		}
	public RelativeLayout setContentInview2(Activity activity){
		RelativeLayout	view=(RelativeLayout)activity.findViewById(R.id.rl_all);
			
			return view;
		}
	public void setTitle(String title,Activity activity){
		tv_title=(TextView)activity.findViewById(R.id.tv_title);
		tv_title.setText(title);
	}
	public ImageView getImageShare(Activity activity){
		ImageView imageView=(ImageView)activity.findViewById(R.id.img_share);
		return imageView;
		
	}
	public void setgoback(final Activity activity){
		rl_back=(RelativeLayout)activity.findViewById(R.id.rl_back);
		rl_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				activity.finish();
			}
		});
	}
	public String getChannelName(String channelKey) {
	    String result = "";
	    if ("dev".equals(channelKey)) { result = "开发版";
	    } else if ("official".equals(channelKey)) { result = "官方版";
	    } else if ("google".equals(channelKey)) { result = "谷歌版";
	    } else if ("appchina".equals(channelKey)) { result = "应用汇版";
	    } else if ("youmi".equals(channelKey)) { result = "有米版";
	    } else if ("waps".equals(channelKey)) { result = "万普版";
	    } else if ("gfan".equals(channelKey)) { result = "机锋版";
	    } else if ("91".equals(channelKey)) { result = "91版";
	    } else if ("hiapk".equals(channelKey)) { result = "安卓版";
	    } else if ("goapk".equals(channelKey)) { result = "安智版";
	    } else if ("mumayi".equals(channelKey)) { result = "木蚂蚁版";
	    } else if ("eoe".equals(channelKey)) { result = "优亿版";
	    } else if ("nduo".equals(channelKey)) { result = "N多版";
	    } else if ("feiliu".equals(channelKey)) { result = "飞流版";
	    } else if ("crossmo".equals(channelKey)) { result = "十字猫版";
	    } else if ("liantong".equals(channelKey)) { result = "联通版";
	    } else if ("huawei".equals(channelKey)) { result = "智汇云版";
	    } else if ("qq".equals(channelKey)) { result = "腾讯版";
	    } else if ("3g".equals(channelKey)) { result = "3G版";
	    } else if ("360".equals(channelKey)) { result = "360版";
	    } else if ("baidu".equals(channelKey)) { result = "百度版";
	    } else if ("sohu".equals(channelKey)) { result = "搜狐版";
	    } else if ("samsung".equals(channelKey)) { result = "三星版";
	    } else if ("coolmart".equals(channelKey)) { result = "酷派版";
	    } else if ("meizu".equals(channelKey)) { result = "魅族版";
	    } else if ("moto".equals(channelKey)) { result = "摩托版";
	    } else if ("xiaomi".equals(channelKey)) { result = "小米版";
	    } else if ("lenovo".equals(channelKey)) { result = "联想版";
	    } else if ("zhuamob".equals(channelKey)) { result = "抓猫版";
	    } else if ("iandroid".equals(channelKey)) { result = "爱卓版";
	    } else if ("imobile".equals(channelKey)) { result = "手机之家版";
	    } else if ("uc".equals(channelKey)) { result = "UC版";
	    } else { result = "山寨版";}
	    return result;
	}

	protected void onStop() {
		super.onStop();
		if (isTopActivity("com.zprmb.udzt")) {

		} else {
			//Toast.makeText(this, "不在前台了1111", 0).show();
			 Editor ed=sp.edit();
			 ed.putString("time", ondata());
			 ed.putInt("isopen",1 );
			 ed.putString("isTop", "1");
			 ed.commit();
			 
			Log.e("退出运行", "1");
		}
	}
	
	/**
	 * 是否息屏
	 * @param c
	 * @return
	 */
	public final boolean isScreenLocked(Context c) {
        KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
        return !mKeyguardManager.inKeyguardRestrictedInputMode();
    }
	

	protected void onPause() {
		super.onPause();
		// TCAgent.onPause(this);
		
		MobclickAgent.onPause(this);
	}

	protected void onResume() {
		super.onResume();
		Log.e("istop",sp.getString("isTop", "") );
		
		if (isTopActivity("com.zprmb.udzt")) {
			if (sp.getString("isTop", "").equals("1")) {
//				if (sp.getInt("isShowGester", 0)==1) {
//					Editor editor = sp.edit();
//					editor.putInt("isShowGester", 0);
//					editor.putString("isTop", "2");
//					editor.commit();
//					return; 
//				}
				if ((Long.valueOf(ondata())-Long.valueOf(sp.getString("time", "")))>900&&sp.getInt("isopen", 0)==1&&!getShare().getString(getMobile(), "").equals("")) {
					LogUtils.e("差", (Long.valueOf(ondata())-Long.valueOf(sp.getString("time", "")))+"");
//					Editor ed1=sp.edit();
//					ed1.putInt("login", 1);
//					 ed1.commit();
					if(sp.getString(getMobile(), "").equals("")){
						if(getMobile().equals("")){
							
						}else{ 
							 
							Intent intent = new Intent(getApplicationContext(),
									GestureEditActivity.class);
							intent.putExtra("towhere", "main");
							startActivity(intent);
							Editor editor = getSharedPreferences("config", MODE_PRIVATE).edit();
							editor.putString("isTop", "2");
							editor.putInt("top", 1);
							editor.commit();
						}
						 
					}else{
						
						Intent intent = new Intent(getApplicationContext(),
								GestureVerifyActivity.class);//GestureVerifyActivity
						startActivity(intent);
						// Toast.makeText(this, "回到前台", 0).show();
						Editor editor = getSharedPreferences("config", MODE_PRIVATE).edit();
						editor.putString("isTop", "2");
						editor.putInt("top", 1);
						editor.commit();
						
					}
					Editor ed=sp.edit();
					ed.putInt("isopen",0 );
					ed.commit();
					return;
				}
				
//				else {
//					if (sp.getBoolean("isTouth", false)) {
//						Editor editor = getSharedPreferences("config", MODE_PRIVATE).edit();
//						editor.putString("token", "");
//						
//						editor.commit();
//					}
			else {
				
				Log.e("差", (Long.valueOf(ondata())-Long.valueOf(sp.getString("time", "")))+"");
				
				 
						
					
				}
				Editor editor = getSharedPreferences("config", MODE_PRIVATE).edit();
				editor.putString("isTop", "2");
				editor.commit();
			}
		} else {
			Log.e("不运行在前台", "1");
		}
		// TCAgent.onResume(this);
		MobclickAgent.onResume(this);
		LogUtils.e("onresume", sp.getInt("isShowGester", 0)+"---"+sp.getString("isTop", ""));
	}
	public String ondata(){
		SimpleDateFormat    formatter    =   new    SimpleDateFormat    ("yyyyMMddHHmmss");       
		Date    curDate    =   new    Date(System.currentTimeMillis());//获取当前时间       
		String    str    =    formatter.format(curDate);
		return str;
	}
	protected void onRestart() {
		super.onRestart();
		/*VolleryUtil vollery = new VolleryUtil() {
			public void onUpDate() {
				try {
					JSONObject jsonObject = new JSONObject(getJson());
					description = jsonObject.optString("description");
					url = jsonObject.optString("url");
					forceUpdate = jsonObject.optBoolean("forceUpdate");
					version = jsonObject.optString("version");
					if (version.equals(getAppVersion())) {
						// init();
					} else {
						showUpVersionDialog(description, url, forceUpdate);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			public void onError() {
			}
		};
		vollery.setRequestMethod(0);
		vollery.execute(this, Constant.URL_NEW + "api/update", "");*/
	}

	protected void onDestroy() {
		super.onDestroy();
		// TODO
		
		//app.removeActvity(this);
	}


	public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
	    boolean result = false;
	    if (window != null) {
	        try {
	            WindowManager.LayoutParams lp = window.getAttributes();
	            Field darkFlag = WindowManager.LayoutParams.class
	                    .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
	            Field meizuFlags = WindowManager.LayoutParams.class
	                    .getDeclaredField("meizuFlags");
	            darkFlag.setAccessible(true);
	            meizuFlags.setAccessible(true);
	            int bit = darkFlag.getInt(null);
	            int value = meizuFlags.getInt(lp);
	            if (dark) {
	                value |= bit;
	            } else {
	                value &= ~bit;
	            }
	            meizuFlags.setInt(lp, value);
	            window.setAttributes(lp);
	            result = true;
	        } catch (Exception e) {

	        }
	    }
	    return result;
	}
	public void showToast(String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}

	public void showLoding() {
		if (ld != null) {
			ld.show();
		}
	}
public String getDeviceType(){
	Build build=new Build();
	return build.MODEL;
}
	public void closeLoding() {
		if (ld != null) {
			ld.close();
		}
	}
	

	public String getAppVersion() {
		// 获取手机的包管理者
		PackageManager pm = getPackageManager();
		try {
			PackageInfo packInfo = pm.getPackageInfo(getPackageName(), 0);
			return packInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			// 不可能发生.
			return "获取版本号失败";
		}
	}

	/*
	 * public int getAppVersionCode(){ PackageManager pm = getPackageManager();
	 * try { PackageInfo packInfo = pm.getPackageInfo(getPackageName(), 0);
	 * return packInfo.versionCode; } catch (NameNotFoundException e) {
	 * e.printStackTrace(); // 不可能发生. return 5; } }
	 */
	public  String encrypt(String source, String publicKey)
			throws Exception {
		Key key = getPublicKey(publicKey);
		/** 得到Cipher对象来实现对源数据的RSA加密 */
		Cipher cipher = Cipher.getInstance(ConfigureEncryptAndDecrypt.RSA_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] b = source.getBytes();
		/** 执行加密操作 */
		byte[] b1 = cipher.doFinal(b);
		return new String(Base64.encodeBase64(b1),
				ConfigureEncryptAndDecrypt.CHAR_ENCODING);
	}
	public static PublicKey getPublicKey(String key) throws Exception {
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
				Base64.decodeBase64(key.getBytes()));
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		return publicKey;
	}
	public String getToken() {
		return sp.getString("token", "");
	}
	public String getURLToken() {
		String token="";
		try {
			 token=URLEncoder.encode(sp.getString("token", ""), "UTF-8");
			return token;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return token;
	}
	public String getUserId() {
		return sp.getString("userId", "");
	}
	public void clearCoupon() {
		Editor editor = sha.edit();
		editor.clear();
		editor.commit();
		
	}
	public String getPublicKey() {
		return publicKey;
	}
	public String getMobile() {
		return sp.getString("mobile", "");
	}
	
	public String getPassWord() {
		return sp.getString("password", "");
	}
	public String getdevice_token() {
		return sp.getString("device_token", "");
	}
	public String geturl() {
		return sp.getString("url", "");
	}
	public int gettab() {
		return sp.getInt("tab", 0);
	}
	public int gethide() {
		return sp.getInt("hide", 0);
	}
	public int getRmb() {
		return sp.getInt("rmb", 1);
	}
	public SharedPreferences getShare() {
		return sp;
	}
	public String getData(){
		String data=String.valueOf( new Timestamp(System.currentTimeMillis()));
		return data;
	}

	/**
	 * 程序是否在前台运行
	 * @return
	 */
	public boolean isTopActivity(String packageName) {
		ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
		if (tasksInfo.size() > 0) {
			// System.out.println("---------------包名-----------"+tasksInfo.get(0).topActivity.getPackageName());
			// 应用程序位于堆栈的顶层
			if (packageName.equals(tasksInfo.get(0).topActivity
					.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	public void getOutput(String str) {
		// System.out.println(str);
	}


	
  public int getScreenWidth(){
	  WindowManager windowManager = getWindowManager();    
      Display display = windowManager.getDefaultDisplay();    
      int screenWidth = screenWidth = display.getWidth();    
      int screenHeight = screenHeight = display.getHeight();   
      return screenWidth;
  }
	private void showUpVersionDialog(String content, final String url,
			final boolean forceUpdate) {
		dialog = new Dialog(BaseActivityTest.this);
		dialog.setCancelable(false);
		Window window = dialog.getWindow();
		window.setBackgroundDrawable(new ColorDrawable(getResources().getColor(
				R.color.float_transparent)));
		window.setGravity(Gravity.CENTER);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		window.setContentView(R.layout.item_splash_upversion_dialog);
		dialog.show();

		TextView tv_upversion_dialog_content = (TextView) window
				.findViewById(R.id.tv_upversion_dialog_content);
		ImageView tv_upversion_dialog_clean = (ImageView) window
				.findViewById(R.id.tv_upversion_dialog_clean);
		TextView tv_upversion_dialog_up = (TextView) window
				.findViewById(R.id.tv_upversion_dialog_up);
		tv_upversion_dialog_content.setText(content);
		tv_upversion_dialog_clean.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				if (dialog != null) {
					dialog.cancel();
				}
				if (forceUpdate) {
					BbtApplication.getInstance().exit();
					android.os.Process.killProcess(android.os.Process.myPid());
				} else {
					// init();
				}
			}
		});
     
		tv_upversion_dialog_up.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				if (dialog != null) {
					dialog.cancel();
				}
				UpdateManager manager = new UpdateManager(BaseActivityTest.this,
						url);
				manager.showDownloadDialog();
			}
		});
	}
	 public  String getMetaData(Context context) {
		 String channel = null;
			PackageManager packageManager = context.getPackageManager();
			ApplicationInfo applicationInfo;
			try {
				applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
				if (applicationInfo != null && applicationInfo.metaData != null) {
					channel =  (String) applicationInfo.metaData.get("UMENG_CHANNEL");
					channel = (String) applicationInfo.metaData.get("UMENG_CHANNEL");
				}
			} catch (NameNotFoundException e) {
				throw new RuntimeException(
						"you must set " + "" + " and " + "" + "  in your manifest file.", e);
			}

			return channel;
		}
	 public static boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
		    Class<? extends Window> clazz = activity.getWindow().getClass();
		    try {
		        int darkModeFlag = 0;
		        Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
		        Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
		        darkModeFlag = field.getInt(layoutParams);
		        Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
		        extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
		        return true;
		    } catch (Exception e) {
		        e.printStackTrace();
		    }
		    return false;
		}
}
